package logparser.bean;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ParserLine {
	private String m_date;
	private String m_loglevel;
	private String m_tag;
	private String m_process_id;
	private String m_processName = "";
	private String m_msg;
	private boolean m_valid = false;
	private int m_origin_line;
	private IQueryProcess m_process_handler = null;
	
	ParserLine(){
		m_process_handler = null;
	}
	
	
	public void SetQueryProcessHandler(IQueryProcess handler){
		m_process_handler = handler;
	}
	
	public void processLine(String line,int origline){
		Matcher matcher;
		String regStr;
		String left;
		
		line = line.trim();
		if(line.isEmpty()){
			return;
		}
		
		// ignore none formatted logs,with tag ""
		// I/wpa_supplicant( 2675): nl80211: Received scan results (8 BSSes)
		regStr = "\\((\\s*)(\\d+)\\):";
		matcher = Pattern.compile(regStr).matcher(line);
		if(!matcher.find()){
			System.out.println("none formated line:" + line);
			return;
		}
		
		m_origin_line = origline;
		m_valid = true;
		
		// extract date and time: 01-13 13:11:25.156
		regStr = "(\\d+)-(\\d+)\\s*(\\d+):(\\d+):(\\d+).(\\d+)(\\s+)";
		matcher = Pattern.compile(regStr).matcher(line);
		if(matcher.find()){
			m_date = line.substring(matcher.start(), matcher.end()).trim();
			left = line.substring(matcher.end());
		}else{
			left = line;
		}
		
		// extract "I/wpa_supplicant( 2675): "
		regStr = "\\(\\s*(\\d+)\\):\\s*";
		matcher = Pattern.compile(regStr).matcher(left);
		if(matcher.find()){
			m_process_id = matcher.group(1);
			m_tag = left.substring(2,matcher.start());
			m_loglevel = left.substring(0,1);
		}else{
			System.out.println("Not formatted line:" + line);
		}
		
		left = left.substring(matcher.end());
		m_msg = left;
		
		if(m_process_handler != null){
			m_processName = m_process_handler.getProcessInfo(Integer.parseInt(m_process_id)).getProcessName();
		}
		
		m_valid = true;
	}
	
	public String getDate(){
		return m_date;
	}
	
	public String getLoglevel(){
		return m_loglevel;
	}
	
	public String getTag(){
		return m_tag;
	}
	
	public String getProcessId(){
		return m_process_id;
	}
	
	public String getMsg(){
		return m_msg;
	}
	
	public boolean getValid(){
		return m_valid;
	}
	
	public int getOrigLine(){
		return m_origin_line;
	}
	
	public String getProcessName(){
		return m_processName;
	}
	
}
